package malitech.yadam.business.acquire;

import malitech.framework.util.DefaultFeedBackHandler;
import malitech.framework.util.TokenReplacer;
import malitech.framework.util.UserFeedBack.FeedbackKind;
import malitech.yadam.model.acquire.JobParameters;
import malitech.yadam.model.acquire.JobStepParameters;

/**
 * This class knows how to run a job given a JobParameters object
 * 
 * @author ech
 * 
 */
public class JobRunner
{
    private JobParameters jobParameters;
    private TokenReplacer tokenReplacer ;
    
    public void run(JobParameters jobParameters, TokenReplacer tokenReplacer)
    {
        this.jobParameters = jobParameters;
        this.tokenReplacer = tokenReplacer;
        DefaultFeedBackHandler.FeedBack.feedback(FeedbackKind.JobStarted, jobParameters.getName());
        callInitOnAllJobSteps();
        callContributeOnAllJobSteps();
        callRunOnAllJobSteps();
        DefaultFeedBackHandler.FeedBack.feedback(FeedbackKind.JobEnded, jobParameters.getName());
    }

    /**
     * run init on all steps
     */
    private void callInitOnAllJobSteps()
    {
        for (JobStepParameters jobStepParameter : jobParameters.getParameters())
        {
            JobStepRunner jobStepRunner = jobStepParameter.getJobStepRunner();
            jobStepRunner.init(jobStepParameter, tokenReplacer);
        }
    }
    
    
    private void callContributeOnAllJobSteps()
    {
        for (JobStepParameters jobStepParameter : jobParameters.getParameters())
        {
            JobStepRunner jobStepRunner = jobStepParameter.getJobStepRunner();
            jobStepRunner.contributeToken();
        }
    }
    
    private void callRunOnAllJobSteps()
    {
        for (JobStepParameters jobStepParameter : jobParameters.getParameters())
        {
            JobStepRunner jobStepRunner = jobStepParameter.getJobStepRunner();
            jobStepRunner.run();
        }
    }
}
